package com.github.xiaoymin.map.ext;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.map.MapClientConfig;
import com.github.xiaoymin.map.common.MapClientConstants;
import com.github.xiaoymin.map.model.MapLocation;
import com.github.xiaoymin.map.model.TencetKey;
import com.github.xiaoymin.map.request.tencent.TencentCoordTranslateRequest;
import com.github.xiaoymin.map.request.tencent.TencentGenCoderRequest;
import com.github.xiaoymin.map.response.tencent.TencentDistrictResponse;
import com.github.xiaoymin.map.response.tencent.TencentGenCoderResponse;
import com.github.xiaoymin.map.response.tencent.TencentIpLocationResponse;
import com.github.xiaoymin.map.util.GsonUtils;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class TencentClient extends TencentAbstractClient{

    Logger logger= LoggerFactory.getLogger(TencentClient.class);
    /**
     * 根据开发配置构造MapClient
     *
     * @param mapClientConfig 开发配置
     */
    public TencentClient(MapClientConfig mapClientConfig) {
        super(mapClientConfig);
    }

    /**
     * 根据经纬度获取详细地址
     * 腾讯地图逆地址解析https://apis.map.qq.com/ws/geocoder/v1
     * @param tencentGenCoderRequest
     * @return
     */
    public Optional<TencentGenCoderResponse> genCoder(TencentGenCoderRequest tencentGenCoderRequest){
        assertNotEmpty(tencentGenCoderRequest,"逆地理编码API请求对象不能为空");
        String tenCentAmapKey = mapClientConfig.getTenCentKey();
        TencetKey tencetKey = new TencetKey(tenCentAmapKey);
        String api= MapClientConstants.TENCENT_API_REGEO+parameter(appendKey(tencentGenCoderRequest.toMap(),tencetKey));
        logger.info("逆地理编码API:{}",api);
        HttpGet get=new HttpGet(api);
        JsonObject jsonObject = responseSuccess(get);
        if(jsonObject!=null){
            JsonObject result = GsonUtils.getJsonObj(jsonObject, "result");
            GsonBuilder gsonBuilder=new GsonBuilder();
            TencentGenCoderResponse amapGenCoderResponse = gsonBuilder.create().fromJson(result, TencentGenCoderResponse.class);
            return Optional.ofNullable(amapGenCoderResponse);
        }
        return Optional.empty();
    }

    /**
     * 坐标转化
     * 坐标转化api https://apis.map.qq.com/ws/coord/v1/translate
     * @param tencentCoordTranslateRequest
     * @return
     */
    public List<MapLocation> getCoordConvert(TencentCoordTranslateRequest tencentCoordTranslateRequest){
        assertNotEmpty(tencentCoordTranslateRequest,"坐标转换参数不能为空");
        String tenCentAmapKey = mapClientConfig.getTenCentKey();
        TencetKey tencetKey = new TencetKey(tenCentAmapKey);
        String api= MapClientConstants.TENCENT_API_COORD_CONVER+parameter(appendKey(tencentCoordTranslateRequest.toMap(),tencetKey));
        logger.info("坐标转换API:{}",api);
        HttpGet get=new HttpGet(api);
        JsonObject jsonObject = responseSuccess(get);
        if (jsonObject!=null){
            JsonElement locations = jsonObject.get("locations");
            GsonBuilder gsonBuilder=new GsonBuilder();
            List<MapLocation> mapLocations = gsonBuilder.create().fromJson(locations, new TypeToken<List<MapLocation>>() {}.getType());
            if(CollectionUtil.isNotEmpty(mapLocations)){
                return mapLocations;
            }
        }
        return null;
    }

    /**
     * 根据ip 获取经纬度以及省市区
     * ip地址获取省市区api https://apis.map.qq.com/ws/location/v1/ip
     * @param ip
     * @return
     */
    public Optional<TencentIpLocationResponse> ipLocation(String ip){
        String tenCentAmapKey = mapClientConfig.getTenCentKey();
        TencetKey tencetKey = new TencetKey(tenCentAmapKey);
        Map<String,String> params= MapUtil.builder("ip",ip).build();
        String api= MapClientConstants.TENCENT_API_IP_LOCATION+parameter(appendKey(params,tencetKey));
        logger.debug("IP地理位置定位API:{}",api);
        HttpGet get=new HttpGet(api);
        JsonObject jsonObject=responseSuccess(get);
        if(jsonObject!=null){
            JsonElement result = jsonObject.get("result");
            GsonBuilder gsonBuilder=new GsonBuilder();
            TencentIpLocationResponse amapIpLocationResponse = gsonBuilder.create().fromJson(result, TencentIpLocationResponse.class);
            return Optional.ofNullable(amapIpLocationResponse);
        }
        return Optional.empty();
    }

    /**
     * 通过关键字获行政区
     * https://apis.map.qq.com/ws/district/v1/search
     * @param keyword
     * @return
     */
    public List<TencentDistrictResponse> keyWordAddress(String keyword){
        String tenCentAmapKey = mapClientConfig.getTenCentKey();
        TencetKey tencetKey = new TencetKey(tenCentAmapKey);
        Map<String,String> params= MapUtil.builder("keyword",keyword).build();
        String api= MapClientConstants.TENCENT_API_DISTRICT_QUERY+parameter(appendKey(params,tencetKey));
        logger.debug("获取行政区API:{}",api);
        HttpGet get=new HttpGet(api);
        JsonObject jsonObject=responseSuccess(get);
        if(jsonObject!=null){
            JsonElement result = jsonObject.get("result");
            String s = result.toString();
            String substring = s.substring(1, s.length() - 1);
            GsonBuilder gsonBuilder=new GsonBuilder();
            List<TencentDistrictResponse> amapDistrictResponses = gsonBuilder.create().fromJson(substring, new TypeToken<List<TencentDistrictResponse>>() {}.getType());
            if(CollectionUtil.isNotEmpty(amapDistrictResponses)){
                return amapDistrictResponses;
            }
        }
        return null;
    }

    /**
     * 腾讯地图的返回成功标志处理返回json
     * @param httpRequest 请求
     * @return 成功后的JsonObject对象
     */
    protected JsonObject responseSuccess(HttpUriRequest httpRequest){
        String content=execute(httpRequest);
        if (StrUtil.isNotBlank(content)) {
            JsonElement jsonElement = jsonParser.parse(content);
            if (jsonElement != null && jsonElement.isJsonObject() && jsonElement.getAsJsonObject() != null) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                String status = GsonUtils.getString(jsonObject, "status");
                if (StrUtil.equals(status, MapClientConstants.TENCENT_RESPONSE_SUCCESS)) {
                    //成功
                    return jsonObject;
                }else{
                    logger.error("<==============腾讯地图请求接口失败==============>");
                }
            }
        }
        return null;
    }
}
